﻿using System;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Popups;

namespace StyleMVVM.View.Impl
{
	public sealed class MessageDialogWrapper : IMessageDialog
	{
		private readonly MessageDialog messageDialog;

		public MessageDialogWrapper(string message)
		{
			messageDialog = new MessageDialog(message);
		}

		public MessageDialogWrapper(string message, string title)
		{
			messageDialog = new MessageDialog(message, title);
		}

		public IMessageDialog AddCommand(string command, object commandAction)
		{
			return AddCommand(command, false, false, commandAction);
		}

		public IMessageDialog AddCommand(string command, bool defaultCommand, object commandAction)
		{
			return AddCommand(command, defaultCommand, false, commandAction);
		}

		public IMessageDialog AddCommand(string command, bool defaultCommand, bool cancelCommand, object commandAction)
		{
			Action<string> cAction = commandAction as Action<string>;

			if (cAction == null)
			{
				throw new ArgumentNullException("oAction must be an Action<string>");
			}

			UICommand newCommand = new UICommand(command, (x) => cAction(x.Label));

			messageDialog.Commands.Add(newCommand);

			if (defaultCommand)
			{
				messageDialog.DefaultCommandIndex = (uint)messageDialog.Commands.Count - 1;
			}

			if (cancelCommand)
			{
				messageDialog.CancelCommandIndex = (uint)messageDialog.Commands.Count - 1;
			}

			return this;
		}

		public IAsyncAction ShowAsync()
		{
			return InternalShowAsync().AsAsyncAction();
		}

		internal async Task InternalShowAsync()
		{
			await messageDialog.ShowAsync();
		}
	}
}